package com.sa.commons.function.randomCode.impl;

import static com.sa.commons.constant.HttpSessionKey.RANDOM_CODE_KEY;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sa.commons.function.randomCode.inter.RandomValidator;


public class RandomValidatorImpl implements RandomValidator {

	private static Log log = LogFactory.getLog(RandomValidatorImpl.class);

	public void initRandom(String randomCode, HttpSession session) {
		session.setAttribute(RANDOM_CODE_KEY, randomCode);
	}

	/**
	 * 验证随机码是否正确 返回的String为错误提示信息 如果为空则验证通过
	 */
	public String valiRandom(String randomCode, HttpSession session) {
		Object sessionRandomCode = session.getAttribute(RANDOM_CODE_KEY);
		session.removeAttribute(RANDOM_CODE_KEY);
		if (sessionRandomCode == null) {
			return "验证码失效请重新输入";
		}

		if (sessionRandomCode instanceof String) {
			if (randomCode.equalsIgnoreCase(sessionRandomCode.toString())) {
				return null;
			} else {
				return "验证码输入错误！";
			}
		} else {
			log.error("系统错误,验证码sessionKey被错误的对象占用。class:"
					+ sessionRandomCode.getClass());
		}
		return null;
	}
}
